//package main
//
//import "fmt"
//
//type person struct {
//	name string
//	age  int
//}
//func f2(x *person) {
//	x.age += 10
//}
//func main() {
//	var p = person{
//		name: "weiQwei",
//		age:  18,
//	}
//	f2(&p)
//	var p2 = new(person)
//	fmt.Printf("%v\n", p)
//	fmt.Printf("%v\n", p2)
//	var p4 = person {
//		"MingOf",
//		100,
//	}
//	fmt.Printf("%v\n",p4)
//	var p5 = newPerson("johnny",27)
//	p5.getName()
//	p5.getNameFromPointer()
//	p5.setAge()
//	fmt.Printf("%v\n",p5)
//}
//func (p person) getName () {
//	fmt.Println(p.name)
//}
//func (p *person) getNameFromPointer () {
//	fmt.Println(p.name)
//}
//func (p *person) setAge () {
//	(*p).age++
//}
//func newPerson (name string, age int) person {
//	return person {
//		name: name,
//		age: age,
//	}
//}
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var cls = &Class{}
	var err error
	err = json.Unmarshal([]byte(data), cls)
	if err != nil {
		return
	}
	fmt.Printf("%T", cls)
	cls.SerializeClass()
	cls.Students[1].changeDetails("zzz", 19, 90)
	cls.SerializeClass()
	var newStu = &Student{
		ID:     "008",
		Name:   "xxx",
		Age:    20,
		Grades: 0,
	}
	cls.addStudent(newStu)
	cls.SerializeClass()
	cls.deleteStudent("008")
	cls.SerializeClass()
}

type Student struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Age    int    `json:"age"`
	Grades int    `json:"grades"`
}
type Class struct {
	Cnum     string     `json:"cnum"`
	Students []*Student `json:"students"`
}

//当方法作用于值类型接收者时，Go语言会在代码运行时将接收者的值复制一份。
//在值类型接收者的方法中可以获取接收者的成员值，但修改操作只是针对副本，无法修改接收者变量本身。
func (c Class) SerializeClass() {
	if len(c.Students) == 0 {
		fmt.Println("There's No Students")
		return
	}
	fmt.Println("---------------------")
	for _, v := range c.Students {
		fmt.Printf("ID: %s  Name: %s  Age: %d  Grades: %d\n", v.ID, v.Name, v.Age, v.Grades)
	}
	fmt.Println("---------------------")
}

// 添加
func (c *Class) addStudent(stu *Student) {
	c.Students = append(c.Students, stu)
}

// 更改
func (s *Student) changeDetails(name string, age int, grades int) {
	s.Name = name
	s.Age = age
	s.Grades = grades
}

// 删除
func (c *Class) deleteStudent(id string) {
	for k, v := range c.Students {
		if v.ID == id {
			c.Students = append(c.Students[:k], c.Students[k+1:]...)
		}
	}
}

var data = `
{ "Cnum": "101",
"Students":
[
    {
    "id": "001",
    "name": "aaa",
    "age": 18,
    "grades": 60
    },
    {
    "id": "002",
    "name": "bbb",
    "age": 18,
    "grades": 60
    },
    {
    "id": "003",
    "name": "ccc",
    "age": 18,
    "grades": 61
    },
    {
    "id": "004",
    "name": "ddd",
    "age": 18,
    "grades": 63
    },
    {
    "id": "005",
    "name": "eee",
    "age": 18,
    "grades": 67
    },
    {
    "id": "006",
    "name": "fff",
    "age": 18,
    "grades": 80
    },
    {
    "id": "007",
    "name": "ggg",
    "age": 18,
    "grades": 90
    }
]
}
`
